package com.mingke.java.task;

import com.mingke.java.entity.AuthEntity;
import com.mingke.java.entity.JDBCInfoEntity;
import com.mingke.java.utils.DataSourceUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

/**
 * 认证操作使用的工具类
 */
public class AuthOperationTask {

    DataSourceUtils sourceUtils;

    JDBCInfoEntity jdbcInfo;


    public boolean check(JDBCInfoEntity jdbcInfo) {

        return false;
    }


    /**
     * 保存认证信息到数据库中
     * @param authEntity
     * @return
     */
    public boolean save(AuthEntity authEntity) {
        String insertRawSQL = generateInsertSQL();
        sourceUtils.doSQL(insertRawSQL, authEntity.getAuth_code(), authEntity.getApp_id(), authEntity.getAuth_host(), 1, new Date(), authEntity.getStart_time(), authEntity.getEnd_time(), 0);
        return true;
    }

    /**
     * 获取当前系统的授权码信息
     * PS: 如果数据中有多条记录，则会按照创建日期取最近的一条记录
     * @return
     */
    public AuthEntity get() {
        AuthEntity authEntity = null;
        String countSql = "SELECT * FROM sys_auth ORDER BY create_time DESC";
        ResultSet resultSet = sourceUtils.doSQL(countSql);
        try {
            while(resultSet.next()) {
                authEntity = new AuthEntity();
                authEntity.setAuth_code(resultSet.getString("auth_code"));
                authEntity.setApp_id(resultSet.getString("app_id"));
                authEntity.setAuth_host(resultSet.getString("auth_host"));
                authEntity.setAuth_state(resultSet.getInt("auth_state"));
                authEntity.setStart_time(resultSet.getDate("start_time"));
                authEntity.setEnd_time(resultSet.getDate("end_time"));
                authEntity.setDeleted(resultSet.getInt("deleted"));
                //仅读取第一条，所以直接退出循环即可
                break;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return authEntity;
    }

    /**
     * 关闭系统资源的函数，需要在使用完毕后调用一下
     */
    public void close() {
        sourceUtils.close();
    }


    /**
     * 生成插入所需要模板SQL
     * @return
     */
    private String generateInsertSQL() {

        ResultSet resultSet = sourceUtils.doSQL("SELECT * FROM "+jdbcInfo.getTableName());

        if(resultSet != null) {
            try {
                //解析ResultSet中数据的结构信息
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                //获取列的个数
                int columnCount = resultSetMetaData.getColumnCount();

                //同步环境下用StringBuffer，多线程并发用StringBuilder
                //拼接原始模版SQL
                StringBuffer headBuffer = new StringBuffer();
                StringBuffer tailBuffer = new StringBuffer();
                headBuffer.append("INSERT INTO ").append(jdbcInfo.getTableName()).append(" ");
                tailBuffer.append(" VALUES (");

                headBuffer.append('(');
                //获取列名
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSetMetaData.getColumnName(i);
                    if(resultSetMetaData.isAutoIncrement(i)) {
                        //跳过自增主键
                        continue;
                    }
                    headBuffer.append(columnName);
                    tailBuffer.append('?');
                    if (i != columnCount) {
                        headBuffer.append(", ");
                        tailBuffer.append(", ");
                    }
                }
                headBuffer.append(')');
                tailBuffer.append(")");
                headBuffer.append(tailBuffer);
                return headBuffer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        sourceUtils.close();
        return "";
    }

    public AuthOperationTask(JDBCInfoEntity jdbcInfoEntity) {
        this.jdbcInfo = jdbcInfoEntity;

        //创建数据库连接
        sourceUtils = new DataSourceUtils();
        sourceUtils.initSimpleConnection(jdbcInfo.getUrl(), jdbcInfo.getUsername(), jdbcInfo.getPassword());
    }
}
